Variables in JavaScript:-

Variable in JavaScript is the name of memory location. They allow us to store and reuse information in a program.

Or Variable in JavaScript is a container that contains the data.

Declaration Keywords:

  1. Var — function-scoped, can be redeclared and updated
  2. let — block-scoped, can be updated but not redeclared in the same scope
  3. const — block-scoped, cannot be updated or redeclared

1. var:-

Var is a Keyword in JavaScript, which is used to declare variables.

It is a functional-scope that means we can access it within the function it is declared.

Var is hoisted, which means it will move to the top of its scope but remains undefined until assigned a value.


        function testVar(){
            var name = "Shivam";
            console.log(name); //Shivam (accessible inside the function)
        }
        testVar();
        console.log(name); //Uncaught ReferenceError: name is not defined  
    

Output:
Shivam
Uncaught ReferenceError: name is not defined

2. let:-


        let age = 25;
        console.log('let age:', age);
        age = 30; // Allowed
        console.log('let age after update:', age);
        // let age = 35; ❌ Not allowed — SyntaxError in same scope
    

Output:
let age: 25
let age after update: 30

3. const

Also introduced in ES6. It is block-scoped and does not allow reassignment or redeclaration.

const country = 'India';
console.log('const country:', country);
// country = 'USA'; ❌ Not allowed — TypeError
// const country = 'UK'; ❌ Not allowed — SyntaxError

Output:
const country: India

Note: